package cn.gudian.cms.Html
import javax.servlet.http.HttpServletRequest
/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 2010-5-6
 * Time: 20:48:25
 * 读取远程网络地址流并且保存到本地文件中
 */
class MakeUtil {
  /**
   *
   * @param urlAdd
   * @param filePath
   * @param fileName
   * @param request
   * @return
   */
  public static boolean makeFile(String urlAdd, String filePath, String fileName, HttpServletRequest request) {
    try {
      def domain = "http://" + request.getServerName() + ":" + request.getServerPort()
      // 创建连接
      URL url = new URL(domain + urlAdd);
      URLConnection urlConnection = url.openConnection();
      File fileDirectory = new File(filePath);
      if (!(fileDirectory.exists()) && !(fileDirectory.isDirectory())) {
        fileDirectory.mkdirs();
      }
      File fileLocalPath = new File(filePath + fileName);

      InputStream inCon = urlConnection.getInputStream();
      // 缓冲
      byte[] buffer = new byte[1024];
      FileOutputStream out = new FileOutputStream(fileLocalPath);

      int count = inCon.read(buffer);
      while (count >= 0) {
        out.write(buffer, 0, count);

        count = inCon.read(buffer);
      }
      out.flush();
      out.close();
      inCon.close();

      return true
    } catch (Exception e) {
      e.printStackTrace();
      return false
    }
  }

  /**
   * 获取一个URL地址字符串中某个参数的值
   */
  public static String getQueryString(String url, String p) {
    def queryString = url.substring(url.indexOf("?") + 1, url.length())
    def parameters = queryString.split("&")
    def pos, paraName, paraValue
    for (int i = 0; i < parameters.length; i++) {
      pos = parameters[i].indexOf('=')
      if (pos == -1) { continue; }
      paraName = parameters[i].substring(0, pos);
      paraValue = parameters[i].substring(pos + 1);
      if (paraName == p) { return paraValue; }
    }
  }
}
